//
//  YGPullDownToRefreshControl.swift
//  sinaWeiBoGui
//
//  Created by liyonggui on 16/5/18.
//  Copyright © 2016年 liyonggui. All rights reserved.
//

import UIKit

/// 高度
private let YGPullDownToRefreshControlHeight: CGFloat = 60

/// 定义状态
enum YGPullDownToRefreshStatus {
    case Normal      // 箭头朝下，下拉刷新
    case Pulling     // 箭头朝上，释放刷新
    case Refreshing  // 转轮旋转，正在刷新
}

class YGPullDownToRefreshControl: UIView {
    
    // MARK: - 公开的方法
    /// 结束刷新
    func endRefreshing() {
        if currentStatus == .Refreshing {
            currentStatus = .Normal
            
            UIView.animateWithDuration(defaultDuration, animations: { () -> Void in
                self.superScrollView?.contentInset.top -= YGPullDownToRefreshControlHeight
            })
        }
    }
    
    /// 开始刷新
    func beginRefreshing() {
        currentStatus = .Refreshing
    }
    
    // MARK: - 属性
    /// 进入刷新状态的闭包
    var pullDownToRefreshingCallBack: (() -> ())?
    
    /// 记录当前状态
    private var currentStatus: YGPullDownToRefreshStatus = .Normal {
        didSet {
            switch currentStatus {
            case.Normal:
                // 风火轮停止旋转
                fhlView.layer.removeAllAnimations()
                // 隐藏风火轮，显示箭头
                fhlView.hidden = true
                arrorView.hidden = false
                
//                YGPrint(items: "下拉刷新")
                messageLabel.text = "下拉刷新"
                UIView.animateWithDuration(defaultDuration, animations: { () -> Void in
                    // 清空transform
                    self.arrorView.transform = CGAffineTransformIdentity
                })
            case.Pulling:
//                YGPrint(items: "释放刷新")
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(defaultDuration, animations: { () -> Void in
                    self.arrorView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case.Refreshing:
//                YGPrint(items: "正在刷新")
                messageLabel.text = "正在刷新"
                // 隐藏箭头，显示风火轮
                arrorView.hidden = true
                fhlView.hidden = false
                messageLabel.text = "正在刷新..."
                
                // 风火轮旋转
                let anim = CABasicAnimation(keyPath: "transform.rotation")
                anim.toValue = M_PI * 2
                anim.duration = defaultDuration
                anim.repeatCount = MAXFLOAT
                anim.removedOnCompletion = false
                
                // 开始动画
                fhlView.layer.addAnimation(anim, forKey: nil)
                
                UIView.animateWithDuration(defaultDuration, animations: { () -> Void in
                    self.superScrollView?.contentInset.top += YGPullDownToRefreshControlHeight
                })
                
                // 调用闭包
                pullDownToRefreshingCallBack?()
            }
        }
    }
    
    /// normal与pulling切换的值
    private var normalToPullingOffset: CGFloat = -124
    
    /// 父控件
    private var superScrollView: UIScrollView?
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        
        let myFrame = CGRect(x: 0, y: -YGPullDownToRefreshControlHeight, width: UIScreen.mainScreen().bounds.width, height: YGPullDownToRefreshControlHeight)
        
        super.init(frame: myFrame)
        
        prepareUI()
    }
    
    // 移除监听
    deinit {
        self.superScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    private func prepareUI() {
//        backgroundColor = UIColor.greenColor()
        
        // 隐藏风火轮
        fhlView.hidden = true
        
        // 添加子控件
        addSubview(arrorView)
        addSubview(fhlView)
        addSubview(messageLabel)
        
        // 添加约束
        // 箭头
        arrorView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        // 风火轮
        fhlView.snp_makeConstraints { (make) -> Void in
            make.centerY.centerX.equalTo(arrorView)
        }
        // 消息label
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrorView.snp_trailing).offset(10)
            make.centerY.equalTo(self)
        }
        
        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        if let superScrollView = newSuperview as? UIScrollView {
            
            // 记录
            self.superScrollView = superScrollView
            
            // 监听
            superScrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        }
    }
    
    // KVO监听回调
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if superScrollView!.dragging {
            // 用户正在拖动
            if currentStatus == .Pulling && superScrollView?.contentOffset.y > normalToPullingOffset {
                // 切换到normal
                currentStatus = .Normal
//                YGPrint(items: "切换到normal")
            } else if currentStatus == .Normal && superScrollView?.contentOffset.y < normalToPullingOffset {
                // 切换到Pulling
                currentStatus = .Pulling
//                YGPrint(items: "切换到Pulling")
            }
            
        } else {
            // 松手 切换到Refreshing
            if currentStatus == .Pulling {
                currentStatus = .Refreshing
//                YGPrint(items: "切换到Refreshing")
            }
        }
    }
    
    // MARK: - 懒加载
    /// 箭头
    private lazy var arrorView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))

    /// 风火轮
    private lazy var fhlView: UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    
    /// label
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.darkGrayColor()
        label.text = "下拉刷新"
        label.sizeToFit()
        
        return label
    }()
    
    
}

























